import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { getLanCode, convertLongLang } from '@/lang'
import Config from '@/config'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: Config.timeout // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['X-AUTH-TOKEN'] = token // 让每个请求携带自定义token
    }
    config.headers['Content-Type'] = 'application/json'
    const lanCode = convertLongLang(getLanCode())
    config.headers['lan-code'] = lanCode
    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      config.data = {
        ...config.data,
        sourceType: 'PC',
        lanCode: lanCode
      }
    }
    return config
  },
  error => {
    // Do something with request error
    Message({
      message: 'request error',
      type: 'error',
      duration: 5 * 1000
    })
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.config.responseType === 'blob') {
      // 文件下载
      let fileName = response.config.fileName
      if (!fileName) {
        fileName = Date.parse(new Date())
      }
      if (res.size === 0) {
        Message({
          message: '导出错误',
          type: 'error',
          dangerouslyUseHTMLString: true,
          duration: 3 * 1000
        })
        return null
      }
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(res, fileName)
      } else {
        var link = document.createElement('a')
        link.href = window.URL.createObjectURL(res)
        link.download = fileName
        link.click()
        // 释放内存
        window.URL.revokeObjectURL(link.href)
      }
      return null
    }
    if (res.code !== '1000') {
      Message({
        message: res.msg || 'error',
        type: 'error',
        dangerouslyUseHTMLString: true,
        duration: 5 * 1000
      })
      if (res.code === '-99') {
        // to re-login
        /*  MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {  */
        store.dispatch('RemoveToken').then(() => {
          location.reload()
          /* this.$router.push({
            path: `/login`
          })*/
        })
      }
      return Promise.reject(res.msg || 'error')
    } else {
      if (res.msg) {
        Message({
          message: res.msg || 'success',
          type: 'success',
          dangerouslyUseHTMLString: true,
          duration: 3 * 1000
        })
      }
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.msg || error,
      type: 'error',
      dangerouslyUseHTMLString: true,
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
